﻿package {
	import flash.net.*;
	import flash.events.*;
	import wronglink.vk.VkApi;
	import flash.display.MovieClip;
	/**
	 * ...
	 * @author kot
	 * 
	 * Searches lastFM artists & tracks 
	 */
	public class LastFMParser extends MovieClip{
		
		private static const api_key : String = MainVK.LastFM_api_key;
		public var ret : Array;
		public function LastFMParser() {
			trace("LastFMParser initialized");
		}
		
		public function getSimilarArtist(artist : String) : void { //gets XML
			var loader:URLLoader = new URLLoader(); 
			loader.addEventListener(Event.COMPLETE, whenXMLLoaded); 
			loader.load(new URLRequest("http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&limit=20&artist=" + artist + "&api_key=" + api_key)); 
		}
		private function whenXMLLoaded(e:Event) { 
			var xml : XML = new XML(e.target.data); 
			//trace(xml);
			var list:XMLList = new XMLList(xml.children().children().child("name"));
			var query: String = list.text()[randRange(0, list.length())];
			trace(query);
			getArray(query);
		}
		
		function randRange(min:Number, max:Number):Number {
			return Math.floor(Math.random() * (max - min + 1)) + min;
		}
		
		private function getArray(search : String) : void { // return music
			if (search == null) {
				return;
			}
			//trace(MainVK(parent).api_url);
			search[0] = 'a';
		
			/*var query : VkApi = new VkApi(MainVK(parent).viewer_id, MainVK.MY_APP_ID, "audio.search", 
										MainVK.MY_SECRET, MainVK.TEST_MODE, "XML", 
										MainVK.VER, MainVK(parent).api_url);
			query.addParameter("q", search);
			trace(query);
			var loader:URLLoader = new URLLoader(); 
			loader.addEventListener(Event.COMPLETE, completed);
		//	trace(query.toString());
			loader.load(new URLRequest(query.toString())); 
			function completed(e:Event) { 
				var xml : XML = new XML(e.target.data); 
				trace(xml);
			}*/
		}
			
		public function getTopTracks(artist : String) : Array {
			//TODO write getTopTracks
			
			return null;
		}
		
	}
	
}